//
//  NSObject+AFNetworking.m
//  WBBaseProject
//
//  Created by 吴斌 on 2017/6/30.
//  Copyright © 2017年 吴斌. All rights reserved.
//

#import "NSObject+AFNetworking.h"
#import <AFNetworking.h>
#define kTimeoutInterval 30

@implementation NSObject (AFNetworking)

/**
 *  @brief 发送一个GET请求
 *
 *  @param url     请求路径
 *  @param params  请求参数
 *  @param success 请求成功后的回调（请将请求成功后想做的事情写到这个block中）
 *  @param failure 请求失败后的回调（请将请求失败后想做的事情写到这个block中）
 *
 */
+ (void)wb_GET:(NSString *)url
        params:(NSDictionary *)params
       success:(success)success
       failure:(failure)failure{
    //1.获得请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置允许请求的类别
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"text/JavaScript", @"text/js", nil];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //3.设置超时时间
    manager.requestSerializer.timeoutInterval = kTimeoutInterval;
    //4.发送GET请求
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DebugLog(@"%@",error.description);
        failure(error);
    }];
}

/**
 *  @brief 发送一个POST请求
 *
 *  @param url     请求路径
 *  @param params  请求参数
 *  @param success 请求成功后的回调（请将请求成功后想做的事情写到这个block中）
 *  @param failure 请求失败后的回调（请将请求失败后想做的事情写到这个block中）
 */
+ (void)wb_POST:(NSString *)url
         params:(NSDictionary *)params
        success:(success)success
        failure:(failure)failure{
    //1.获得请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置允许请求的类别
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", nil];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //3.设置超时时间
    manager.requestSerializer.timeoutInterval = kTimeoutInterval;
  
//    设置请求头
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:Token];
    if (!WB_IsNilString(token)) {
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    }
    
    //4.发送POST请求
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //登陆超时处理  获取 header 中的timeout的方法：
//        NSString *timeOut;
//        if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
//            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
//            timeOut = [response allHeaderFields][@"tokenstatus"];
//            if ([timeOut isEqualToString:@"timeout"]) {
//                [ZWLoadingView showAlertHUD:@"登录超时" duration:DelayedTime];
//                //延时1s返回
//                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(DelayedTime/*延迟执行时间*/ * NSEC_PER_SEC));
//                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//                    [Factory loadLoginScreen];
//                });
//                return ;
//            }
//        }
        
        //标准的json格式
        NSString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        //再将json转成字典
        NSDictionary *dic = [Factory dictionaryWithJsonString:str];
        NSLog(@"%@",dic);
        success(dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DebugLog(@"%@",error.description);
        failure(error);
    }];
}

/**
 *  @brief 发送图片数据
 *
 *  @param url         请求路径
 *  @param params      请求参数
 *  @param imageData   图片二进制数据
 *  @param name        图片名称
 *  @param success     请求成功后的回调（请将请求成功后想做的事情写到这个block中）
 *  @param failure     请求失败后的回调（请将请求失败后想做的事情写到这个block中）
 */
+ (void)wb_POST:(NSString *)url
         params:(NSDictionary *)params
         NSData:(NSData *)imageData
            key:(NSString *)name
        success:(success)success
        failure:(failure)failure{
    //1.获得请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.设置允许请求的类别
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //3.设置超时时间
    manager.requestSerializer.timeoutInterval = kTimeoutInterval;
    
    //添加token
//    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:Token];
//    if (![token isEqualToString:@""]) {
//        [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
//    }
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DebugLog(@"%@",error.description);
        failure(error);
    }];
}

@end
